package com.txby.pf.modules.busi.controller;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.txby.pf.modules.sys.controller.AbstractController;

/**
 * 新闻编辑
 */
@RequestMapping("/busi/news")
public class NewsPicUploadController extends AbstractController {
	
	/**
	 * 新闻图片上传
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/upload")  
    public void upload(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, HttpServletResponse response, ModelMap model) throws UnsupportedEncodingException {  
	    request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
	    Uploader up = new Uploader(request);
	    up.setSavePath("upload");
	    String[] fileType = {".gif" , ".png" , ".jpg" , ".jpeg" , ".bmp"};
	    up.setAllowFiles(fileType);
	    up.setMaxSize(10000); //单位KB
	    try {
			up.upload();
		} catch (Exception e) {
			e.printStackTrace();
		}

	    String callback = request.getParameter("callback");

	    String result = "{\"name\":\""+ up.getFileName() +"\", \"originalName\": \""+ up.getOriginalName() +"\", \"size\": "+ up.getSize() +", \"state\": \""+ up.getState() +"\", \"type\": \""+ up.getType() +"\", \"url\": \""+ up.getUrl() +"\"}";

	    result = result.replaceAll( "\\\\", "\\\\" );

	    if( callback == null ){
	    	try {
				response.getWriter().print( result );
			} catch (IOException e) {
				e.printStackTrace();
			}
	    }else{
	    	try {
				response.getWriter().print("<script>"+ callback +"(" + result + ")</script>");
			} catch (IOException e) {
				e.printStackTrace();
			}
	    }
    }  
	
	/**
	 * 新闻图片上传
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/upload2")  
	public String upload2(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, HttpServletResponse response, ModelMap model) throws UnsupportedEncodingException {  
		System.out.println("开始");
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		String path = request.getSession().getServletContext().getRealPath("upload");  
		String fileName = file.getOriginalFilename();  
		System.out.println(path);  
		File targetFile = new File(path, fileName);  
		if(!targetFile.exists()){  
			targetFile.mkdirs();  
		}  
		
		//保存  
		try {  
			file.transferTo(targetFile);  
		} catch (Exception e) {  
			e.printStackTrace();  
		}  
		model.addAttribute("fileUrl", request.getContextPath()+"/upload/"+fileName);  
		
		return "result";  
	}  
	
}
